const jwt = require('jsonwebtoken');
module.exports = () => {
    return async (ctx,next) => {
        let writePath = ['/api/login','/api/registry'];
        //ctx.path ctx.url
        if(writePath.includes(ctx.path)){
            await next();
        }else{
            //进行token校验
            let token = ctx.get('token');
            try{
                let info = jwt.verify(token,'yuque');   //{ uid: 1, iat: 1580868923, exp: 1580883323 }
                console.log(info)
                ctx.info = info;
                await next();
            }catch(e){
                //判断是否是因为token出现的问题
                //TokenExpiredError  JsonWebTokenError 
                if(e.name === 'TokenExpiredError' || e.name === 'JsonWebTokenError'){
                    ctx.status = 401;  //401代表用户没有访问权限，需要进行身份认证
                    ctx.body = {
                        code:4,
                        msg:e
                    }
                }else{
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }
    }
}